//
//  CYBindCardViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/19.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYBindCardViewController.h"

#import "CYBindCardWillPaymentCell.h"
#import "CYBindCardSectionCell.h"
#import "CYBindCardNormalCell.h"
#import "CYBindCardSMSCell.h"

#import "CYDataAPIUserAccountModel.h"

#import "CYRechargeSuccessViewController.h"
#import "CYInvestSucceededViewController.h"
#import "CYWebViewController.h"
#import "CYRechargeInProgressViewController.h"

#import "CYSMSExpireManager.h"



@interface CYBindCardViewController ()

@property(nonatomic, strong)CYBindCardWillPaymentCellObject *willPaymentCell;
@property(nonatomic, strong)CYBindCardNormalCellObject *nameCell;
@property(nonatomic, strong)CYBindCardNormalCellObject *idCell;
@property(nonatomic, strong)CYBindCardNormalCellObject *cardCell;
@property(nonatomic, strong)CYBindCardNormalCellObject *phoneCell;
@property(nonatomic, strong)CYBindCardSMSCellObject *smsCell;

@property(nonatomic, strong)UIView *tableFooterView;
@property(nonatomic, strong)UIButton *submitButton;

@property(nonatomic, strong)NSString *mobile_auth_code;
@property(nonatomic, strong)NSString *recharge_no;

@property(nonatomic, assign)BOOL successed;
@property(nonatomic, strong)CYDataAPIUserAccountModel *apiUserAccountModel;

@end


@implementation CYBindCardViewController

- (void)close
{
    switch(self.type)
    {
        case CYBindCardTypeNormal:
            [MobClick event:UM_EVENT_0067];
            break;
        case CYBindCardTypePayment:
            [MobClick event:UM_EVENT_0040];
            break;
        case CYBindCardTypeRecharge:
            [MobClick event:UM_EVENT_0061];
            break;
    }
    [super close];
}

- (void)loadUI
{
    UIButton *limitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [limitButton setTintColor:HEXCOLOR(@"444444")];
    [limitButton setTitle:@"限额说明" forState:UIControlStateNormal];
    limitButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [limitButton sizeToFit];
    [limitButton addTarget:self action:@selector(onLimitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:limitButton];
    
    NSString *title = nil;
    NSString *button = nil;
    switch(self.type)
    {
        case CYBindCardTypeNormal:
        {
            title = @"添加银行卡";
            button = @"确认添加";
            break;
        }
        case CYBindCardTypePayment:
        {
            title = @"支付";
            button = @"确认支付";
            break;
        }
        case CYBindCardTypeRecharge:
        {
            title = @"充值";
            button = @"确认支付";
            break;
        }
    }
    self.navigationItem.title = title;
    
    {
        self.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 124)];
        self.tableView.tableFooterView = self.tableFooterView;
        {
            self.submitButton = [UIButton cy_mainButtonWithTitle:button];
            [self.submitButton addTarget:self action:@selector(onSubmitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
            [self.tableFooterView addSubview:self.submitButton];
        }
    }
    
    [self loadCells];
}

- (void)layoutUI
{
    self.tableFooterView.width = self.tableView.width;
    {
        self.submitButton.width = self.tableFooterView.width - 40;
        self.submitButton.height = 44;
        self.submitButton.centerX = self.tableFooterView.width / 2;
        self.submitButton.centerY = self.tableFooterView.height / 2;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    @weakify(self);
    [CYStandardDataAPI user_userAccountWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            self.apiUserAccountModel = [CYDataAPIUserAccountModel mj_objectWithKeyValues:response.content];
            NSString *name = SAFE_STRING(self.apiUserAccountModel.realName);
            NSString *idNo = SAFE_STRING(self.apiUserAccountModel.cardNo);
            if(name.length && idNo.length)
            {
                {
                    NSMutableString *mask = [NSMutableString string];
                    for(NSInteger i = 1; i < name.length; i++)
                    {
                        [mask appendString:@"*"];
                    }
                    name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:1], mask];
                }
                {
                    NSMutableString *mask = [NSMutableString string];
                    for(NSInteger i = 7; i < idNo.length; i++)
                    {
                        [mask appendString:@"*"];
                    }
                    if(idNo.length > 4)
                    {
                        idNo = [NSString stringWithFormat:@"%@%@%@", [idNo substringToIndex:3], mask, [idNo substringFromIndex:idNo.length - 4]];
                    }
                }
                self.nameCell.content = name;
                self.nameCell.lockInput = YES;
                self.idCell.content = idNo;
                self.idCell.lockInput = YES;
                [self.tableView reloadData];
            }
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if(self.successed)
    {
        self.navigationController.viewControllers = @[self.navigationController.viewControllers.firstObject, self.navigationController.viewControllers.lastObject];
    }
}

#pragma mark - Actions
- (void)submitAction
{
    switch(self.type)
    {
        case CYBindCardTypeNormal:
            [MobClick event:UM_EVENT_0068];
            break;
        case CYBindCardTypePayment:
            [MobClick event:UM_EVENT_0041];
            break;
        case CYBindCardTypeRecharge:
            [MobClick event:UM_EVENT_0062];
            break;
    }
    [self.view endEditing:YES];
    
    NSString *real_name = SAFE_STRING(self.apiUserAccountModel.realName).length ? SAFE_STRING(self.apiUserAccountModel.realName) : self.nameCell.content;
    NSString *card_no = SAFE_STRING(self.apiUserAccountModel.cardNo).length ? SAFE_STRING(self.apiUserAccountModel.cardNo) : self.idCell.content;

    NSString *bank_card_no = self.cardCell.content;
    NSString *mobile = self.phoneCell.content;
    NSString *mobile_auth_code = self.smsCell.smsCode;
    
    if(bank_card_no.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入银行卡"];
        if(self.type == CYBindCardTypePayment)
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入银行卡" complete:nil];
        }
        return;
    }
    if(card_no.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入身份证"];
        if(self.type == CYBindCardTypePayment)
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入身份证" complete:nil];
        }
        return;
    }
    if(![mobile cy_isPhoneNumber])
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确手机号"];
        if(self.type == CYBindCardTypePayment)
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入正确手机号" complete:nil];
        }
        return;
    }
    if(mobile_auth_code.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        if(self.type == CYBindCardTypePayment)
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入验证码" complete:nil];
        }
        return;
    }
    if(real_name.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入真实姓名"];
        if(self.type == CYBindCardTypePayment)
        {
            [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入真实姓名" complete:nil];
        }
        return;
    }
    
    @weakify(self);
    [SVProgressHUD show];
    switch(self.type)
    {
        case CYBindCardTypeNormal:
        {
            [CYStandardDataAPI project_bindCardWithBank_card_no:bank_card_no card_no:card_no mobile:mobile mobile_auth_code:mobile_auth_code real_name:real_name complete:^(CYResponse *response) {
                if(response.code == 0)
                {
                    @strongify(self);
                    [SVProgressHUD showSuccessWithStatus:@"添加银行卡成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                }
            }];
            break;
        }
        case CYBindCardTypePayment:
        {
            if(self.recharge_no == nil)
            {
                [SVProgressHUD showErrorWithStatus:@"请获取验证码"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请获取验证码" complete:nil];
                return;
            }
            [SVProgressHUD show];
            [CYStandardDataAPI project_InvestWithMobile_auth_code:mobile_auth_code pay_way:self.apiModel.payWay recharge_no:self.recharge_no user_coupon_id:self.user_coupon_id complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0 || response.code == 22017)
                {
                    [SVProgressHUD dismiss];
                    self.successed = YES;
                    [CYStandardSMSExpireManager resetExpireDate:[NSDate date] type:CYSMSExpireTypePayment];
                    
                    if(response.code == 0)
                    {
                        CYInvestRecordDetailViewModel *model = [[CYInvestRecordDetailViewModel alloc] init];
                        model.progress = CYInvestProgressAccount;
                        if([response.content isKindOfClass:[NSDictionary class]])
                        {
                            model.iid = SAFE_NUMBER(response.content[@"investDetailId"]);
                            NSDictionary *process = response.content[@"process"];
                            if([process isKindOfClass:[NSDictionary class]])
                            {
                                NSDate *successDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"investTime"]) doubleValue] / 1000.0];
                                NSDate *accountDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"goldTime"]) doubleValue] / 1000.0];
                                NSDate *outDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"loanTime"]) doubleValue] / 1000.0];
                                NSDate *bearingDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"interestTime"]) doubleValue] / 1000.0];
                                NSDate *inDate = [NSDate dateWithTimeIntervalSince1970:[SAFE_NUMBER(process[@"repaymentTime"]) doubleValue] / 1000.0];
                                NSString *format = @"yyyy-MM-dd";
                                model.successDate = [successDate cy_stringWithFormat:format];
                                model.accountDate = [accountDate cy_stringWithFormat:format];
                                model.outDate = [outDate cy_stringWithFormat:format];
                                model.bearingDate = [bearingDate cy_stringWithFormat:format];
                                model.inDate = [inDate cy_stringWithFormat:format];
                            }
                        }
                        
                        CYInvestSucceededViewController *investSucceededViewController = [[CYInvestSucceededViewController alloc] init];
                        investSucceededViewController.model = model;
                        [self.navigationController pushViewController:investSucceededViewController animated:YES];
                        
                        [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:YES msg:response.message complete:nil];
                    }
                    else
                    {
                        CYRechargeInProgressViewController *rechargeInProgressViewController = [[CYRechargeInProgressViewController alloc] init];
                        rechargeInProgressViewController.type = CYRechargeInProgressTypeInvest;
                        [self.navigationController pushViewController:rechargeInProgressViewController animated:YES];
                    }
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                    [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:NO msg:response.message complete:nil];
                }
            }];
            break;
        }
        case CYBindCardTypeRecharge:
        {
            if(self.recharge_no == nil)
            {
                [SVProgressHUD showErrorWithStatus:@"请获取验证码"];
                return;
            }
            [SVProgressHUD show];
            [CYStandardDataAPI user_walletRechargeWithMobile_auth_code:mobile_auth_code pay_way:CYDataAPIPayWayBaoFu recharge_no:self.recharge_no complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0 || response.code == 22017)
                {
                    [SVProgressHUD dismiss];
                    self.successed = YES;
                    if(response.code == 0)
                    {
                        [CYStandardSMSExpireManager resetExpireDate:[NSDate date] type:CYSMSExpireTypePayment];
                        CYRechargeSuccessViewController *rechargeSuccessViewController = [[CYRechargeSuccessViewController alloc] init];
                        [self.navigationController pushViewController:rechargeSuccessViewController animated:YES];
                    }
                    else
                    {
                        CYRechargeInProgressViewController *rechargeInProgressViewController = [[CYRechargeInProgressViewController alloc] init];
                        rechargeInProgressViewController.type = CYRechargeInProgressTypeRecharge;
                        [self.navigationController pushViewController:rechargeInProgressViewController animated:YES];
                    }
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                }
            }];
            break;
        }
    }
}

- (void)smsAction
{
    [self.view endEditing:YES];
    
    switch(self.type)
    {
        case CYBindCardTypeNormal:
        {
            NSString *mobile = self.phoneCell.content;
            if(![mobile cy_isPhoneNumber])
            {
                [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
                return;
            }
            @weakify(self);
            [SVProgressHUD show];
            [CYStandardDataAPI user_getSmsCodeWithMobile:mobile sms_type:CYDataAPISMSCodeTypeBindCard complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0)
                {
                    NSNumber *seconds = response.content[@"seconds"];
                    if(![seconds isKindOfClass:[NSNumber class]])
                    {
                        seconds = @60;
                    }
                    [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypeBindCard];
                    [self.tableView reloadData];
                    [SVProgressHUD dismiss];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                }
            }];
            break;
        }
        case CYBindCardTypePayment:
        {
            NSString *bank_card_no = self.cardCell.content;
            NSString *mobile = self.phoneCell.content;
            NSString *real_name = SAFE_STRING(self.apiUserAccountModel.realName).length ? SAFE_STRING(self.apiUserAccountModel.realName) : self.nameCell.content;
            NSString *card_no = SAFE_STRING(self.apiUserAccountModel.cardNo).length ? SAFE_STRING(self.apiUserAccountModel.cardNo) : self.idCell.content;
            if(bank_card_no.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入银行卡"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入银行卡" complete:nil];
                return;
            }
            if(card_no.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入身份证"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入身份证" complete:nil];
                return;
            }
            if(![mobile cy_isPhoneNumber])
            {
                [SVProgressHUD showErrorWithStatus:@"请输入正确手机号"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入正确手机号" complete:nil];
                return;
            }
            if(real_name.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入真实姓名"];
                [CYStandardDataAPI user_investmentLog_addWithCode:10 flowId:self.apiModel.operationId isSuccess:NO msg:@"请输入真实姓名" complete:nil];
                return;
            }
            [SVProgressHUD show];
            @weakify(self);
            [CYStandardDataAPI project_preInvestWithAmount:self.apiModel.amountBank bank_card_no:bank_card_no card_no:card_no mobile:mobile pay_way:self.apiModel.payWay project_id:self.fid real_name:real_name user_coupon_id:self.user_coupon_id complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0)
                {
                    NSNumber *seconds = response.content[@"seconds"];
                    if(![seconds isKindOfClass:[NSNumber class]])
                    {
                        seconds = @60;
                    }
                    [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypePayment];
                    self.recharge_no = response.content[@"rechargeNo"];
                    self.nameCell.lockInput = YES;
                    self.idCell.lockInput = YES;
                    self.cardCell.lockInput = YES;
                    self.phoneCell.lockInput = YES;
                    [self.tableView reloadData];
                    [SVProgressHUD dismiss];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                    [CYStandardDataAPI user_investmentLog_addWithCode:response.code flowId:self.apiModel.operationId isSuccess:NO msg:response.message complete:nil];
                }
            }];
            break;
        }
        case CYBindCardTypeRecharge:
        {
            NSString *bank_card_no = self.cardCell.content;
            NSString *mobile = self.phoneCell.content;
            NSNumber *amount = self.willPayment;
            
            NSString *real_name = SAFE_STRING(self.apiUserAccountModel.realName).length ? SAFE_STRING(self.apiUserAccountModel.realName) : self.nameCell.content;
            NSString *card_no = SAFE_STRING(self.apiUserAccountModel.cardNo).length ? SAFE_STRING(self.apiUserAccountModel.cardNo) : self.idCell.content;

            if(bank_card_no.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入银行卡"];
                return;
            }
            if(card_no.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入身份证"];
                return;
            }
            if(![mobile cy_isPhoneNumber])
            {
                [SVProgressHUD showErrorWithStatus:@"请输入正确手机号"];
                return;
            }
            if(real_name.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"请输入真实姓名"];
                return;
            }
            [SVProgressHUD show];
            @weakify(self);
            [CYStandardDataAPI user_preWalletRechargeWithAmount:[amount.amountString stringByReplacingOccurrencesOfString:@"," withString:@""] bank_card_no:bank_card_no card_no:card_no mobile:mobile pay_way:CYDataAPIPayWayBaoFu real_name:real_name complete:^(CYResponse *response) {
                @strongify(self);
                if(response.code == 0)
                {
                    NSNumber *seconds = response.content[@"seconds"];
                    if(![seconds isKindOfClass:[NSNumber class]])
                    {
                        seconds = @60;
                    }
                    [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypePayment];
                    self.recharge_no = response.content[@"rechargeNo"];
                    self.nameCell.lockInput = YES;
                    self.idCell.lockInput = YES;
                    self.cardCell.lockInput = YES;
                    self.phoneCell.lockInput = YES;
                    [self.tableView reloadData];
                    [SVProgressHUD dismiss];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:response.message];
                }
            }];
            break;
        }
    }
}

- (void)limitAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/bank_info.html"];
    webViewController.defaultTitle = @"限额说明";
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark - Control Events
- (void)onSubmitButtonTouchUpInside
{
    [self submitAction];
}

- (void)onLimitButtonTouchUpInside
{
    [self limitAction];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - Private Mehtod
- (void)loadCells
{
    self.willPaymentCell = [CYBindCardWillPaymentCellObject objectWithCellClass:[CYBindCardWillPaymentCell class]];
    self.willPaymentCell.amount = self.willPayment;
    
    self.nameCell = [CYBindCardNormalCellObject objectWithCellClass:[CYBindCardNormalCell class]];
    self.nameCell.title = @"真实姓名";
    self.nameCell.placeholder = @"请输入姓名";
    self.nameCell.keyboardType = UIKeyboardTypeDefault;
    self.nameCell.isBottom = NO;
    
    self.idCell = [CYBindCardNormalCellObject objectWithCellClass:[CYBindCardNormalCell class]];
    self.idCell.title = @"身份证号";
    self.idCell.placeholder = @"请输入身份证号";
    self.idCell.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.idCell.isBottom = YES;

    self.cardCell = [CYBindCardNormalCellObject objectWithCellClass:[CYBindCardNormalCell class]];
    self.cardCell.title = @"我的银行卡";
    self.cardCell.placeholder = @"请输入卡号";
    self.cardCell.keyboardType = UIKeyboardTypeNumberPad;
    self.cardCell.isBottom = NO;

    self.phoneCell = [CYBindCardNormalCellObject objectWithCellClass:[CYBindCardNormalCell class]];
    self.phoneCell.title = @"手机号码";
    self.phoneCell.placeholder = @"请输入银行卡预留手机号码";
    self.phoneCell.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneCell.isBottom = NO;
    
    @weakify(self);
    self.smsCell = [CYBindCardSMSCellObject objectWithCellClass:[CYBindCardSMSCell class]];
    switch(self.type)
    {
        case CYBindCardTypeNormal:
        {
            self.smsCell.type = CYSMSExpireTypeBindCard;
            break;
        }
        default:
        {
            self.smsCell.type = CYSMSExpireTypePayment;
            break;
        }
    }
    self.smsCell.smsCodeAction = ^{
        @strongify(self);
        [self smsAction];
    };
    
    NSMutableArray *cells = [NSMutableArray array];
    {
        if(self.type != CYBindCardTypeNormal)
        {
            [cells addObject:self.willPaymentCell];
        }
        {
            CYBindCardSectionCellObject *cell = [CYBindCardSectionCellObject objectWithCellClass:[CYBindCardSectionCell class]];
            cell.title = @"持卡人信息";
            [cells addObject:cell];
        }
        {
            [cells addObject:self.nameCell];
        }
        {
            [cells addObject:self.idCell];
        }
        {
            CYBindCardSectionCellObject *cell = [CYBindCardSectionCellObject objectWithCellClass:[CYBindCardSectionCell class]];
            cell.title = @"请使用与持卡人信息一致的储蓄卡";
            [cells addObject:cell];
        }
        {
            [cells addObject:self.cardCell];
        }
        {
            [cells addObject:self.phoneCell];
        }
        {
            [cells addObject:self.smsCell];
        }
    }
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
}

@end
